package com.netty8018.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author liyanhao
 * @Date 2023-02-05 6:29
 */
public class MyServer {
    public static void main(String[] args) {
        //创建两个线程组
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入一个netty 提供IdleStateHandler
                            /**
                             * 说明
                             * 1.IdleStateHandler 是nettty提供的处于空闲状态的处理器
                             * 2.long readerIdleTime 表示多长时间没有读 就会发送一个心跳检测包检测连接是否存在
                             * 3.long writerIdleTime 表示多长时间没有写 就会发送一个心跳检测包检测连接是否存在
                             * 4.long allIdelTime 表示多长时间没有读写 就会发送一个心跳检测包检测连接是否存在
                             * 6.当IdleStateEvent 触发后 就会传递给管道的下一个handler去处理
                             * 通过调用触发一下handler的userEventTiggered 在该方法中处理IdleStateEvent(读写空闲、读空闲、写空闲)
                             */
                            pipeline.addLast(new IdleStateHandler(13, 5, 2, TimeUnit.SECONDS));
                            //加入一个对空闲检测进一步检测处理的handler(自定义)
                            pipeline.addLast(new MyserverHandler());
                        }
                    });
            //启动服务器
            ChannelFuture channelFuture = bootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
